﻿using System.Drawing;
using System.Xml;

namespace Wpf_Demo
{
    public class XmlHelper
    {
        private static XmlHelper instancen = new XmlHelper();

        public static XmlHelper Instancen => instancen;

        private List<ColorType> _ColorTypes = new List<ColorType>();

        public List<ColorType> ColorTypes { get { return _ColorTypes; } }

        private XmlHelper()
        {
            ReadXmlRGB();
        }

        private void ReadXmlRGB()
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;//忽略文档里面的注释
            XmlReader reader = XmlReader.Create("EVDNT_TFM_Amplitude.pal", settings);

            xmlDoc.Load(reader);
            reader.Close();
            // 得到根节点bookstore
            XmlNode xn = xmlDoc.SelectSingleNode("Palette");
            xn = xn.SelectSingleNode("MainColors");
            // 得到根节点的所有子节点
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xn1 in xnl)
            {
                ColorType Colortype = new ColorType();
                // 将节点转换为元素，便于得到节点的属性值
                XmlElement xe = (XmlElement)xn1;
                Colortype.Red = Convert.ToInt32(xe.GetAttribute("R").ToString());
                Colortype.Green = Convert.ToInt32(xe.GetAttribute("G").ToString());
                Colortype.Blue = Convert.ToInt32(xe.GetAttribute("B").ToString());
                _ColorTypes.Add(Colortype);
            }
        }

        /// <summary>
        /// B扫是每个点，C扫最高点
        /// </summary>
        /// <param name="value"></param>
        public Color GetColor(double value)
        {
            var list = XmlHelper.Instancen.ColorTypes;
            Color color = Color.Black;
            double c;
            c = value;
            double num = c * 2.55;
            if (num > 255) num = 255;
            else if (num < 0) num = 0;
            num = Math.Round(num, 0);
            int id = Convert.ToInt32(num);
            color = Color.FromArgb(list[id].Red, list[id].Green, list[id].Blue);
            return color;
        }
    }

    public class ColorType
    {
        public ColorType()
        {
        }
        /// <summary>
        /// R
        /// </summary>
        private int red;
        public int Red
        {
            get { return red; }
            set { red = value; }
        }
        /// <summary>
        /// G
        /// </summary>
        private int green;
        public int Green
        {
            get { return green; }
            set { green = value; }
        }
        /// <summary>
        /// B
        /// </summary>
        private int blue;
        public int Blue
        {
            get { return blue; }
            set { blue = value; }
        }
    }
}
